//
//  LoginVC.swift
//  LeGou
//
//  Created by lxm on 2022/7/23.
//

import UIKit
import YYText
class LoginVC: ZMViewController {

    //MARK:--------------------属性--------------------
    
    //MARK:--------------------UI控件--------------------
    var bottomLabel = YYLabel(frame: CGRect(x: 0, y: 0, width: 200, height: 300))
    
    @IBOutlet weak var loginButton: UIButton!
    
    @IBOutlet weak var phoneButton: UIButton!
    
    let porotocolButton = UIButton().then { b in
        b.setImage(UIImage.init(named: "login_s"), for: .selected)
        b.setImage(UIImage.init(named: "login_u"), for: .normal)
    }
    
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
    }
    
    //MARK:--------------------UI--------------------
    func setUI() {
        hbd_barHidden = true
        let bottomTitlte : NSString = "我已详细阅读并同意《乐购惠生活用户注册服务协议》《隐私协议》"
        bottomLabel.text = bottomTitlte as String
        let rangeOne = bottomTitlte.range(of: "《乐购惠生活用户注册服务协议》")
        let rangeTwo = bottomTitlte.range(of: "《隐私协议》")
        bottomLabel.textColor = UIColor.zm.color999999()
        let a = NSMutableAttributedString(string: "我已详细阅读并同意《乐购惠生活用户注册服务协议》《隐私协议》")
        a.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.zm.color999999()], range: NSRange(location: 0, length: bottomTitlte.length))
        a.yy_setTextHighlight(rangeOne, color: Style.mainColor, backgroundColor: UIColor.clear, userInfo: ["d":"s"], tapAction: { containerView, text, range, rect in
            CommonService.shared.goWeb(type: .registerProtocol)
        }, longPressAction: { containerView, text, range, rect in
            
        })
        
        a.yy_setTextHighlight(rangeTwo, color: Style.mainColor, backgroundColor: UIColor.clear, userInfo: ["d":"s"], tapAction: { containerView, text, range, rect in
            CommonService.shared.goWeb(type: .privateProtocol)
        }, longPressAction: { containerView, text, range, rect in
            
        })
                
        bottomLabel.attributedText = a
        bottomLabel.numberOfLines = 0
        bottomLabel.sizeToFit()
        let size = bottomLabel.sizeThatFits(CGSize(width: SCREEN_W - 100, height: 200))
        view.addSubview(bottomLabel)
        bottomLabel.sizeToFit()
        bottomLabel.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-40)
            make.right.equalToSuperview().offset(-40)
            make.left.equalToSuperview().offset(60)
            make.height.equalTo(size.height)
        }
        
        view.addSubview(porotocolButton)
        porotocolButton.sizeToFit()
        porotocolButton.snp.makeConstraints { make in
            make.top.equalTo(bottomLabel.snp.top)
            make.right.equalTo(bottomLabel.snp.left).offset(-8)
        }
        
        if AppHelper.appVerify() {
            loginButton.setTitle("账号登陆", for: .normal)
            loginButton.setImage(nil, for: .normal)
            phoneButton.isHidden = true
        } else {
            loginButton.setTitle("微信登陆", for: .normal)
            loginButton.setImage(UIImage.init(named: "wechat"), for: .normal)
            phoneButton.isHidden = false
        }
    }
    
    func addConstraints() {
        
    }
    
    //MARK:--------------------methods--------------------
    // 是否同意协议
    func checkAgree() -> Bool {
        return porotocolButton.isSelected
    }
    
    func bindAction() {
        porotocolButton.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.porotocolButton.isSelected = !self.porotocolButton.isSelected
        }).disposed(by: disposeBag)
    }

    @IBAction func onPhoneLogin(_ sender: Any) {
        if checkAgree() == false {
//                ZMToast.showToast(title: "请勾选同意协议")
            let v = ZMUtil.loadNibViewFullScreen(nibName: ProtocolPOP.self)
            view.addSubview(v)
            v.protocolAgreeBlock = { [unowned self] in
                self.porotocolButton.isSelected = true
                router.push("xm://main/Login/phone_input")
            }
            return
        }
        router.push("xm://main/Login/phone_input")
    }
    
    @IBAction func onWechat(_ sender: Any) {
        if AppHelper.appVerify() {
            self.onPhoneLogin(sender)
            return
        }
        if checkAgree() == false {
//            ZMToast.showToast(title: "请勾选同意协议")
            let v = ZMUtil.loadNibViewFullScreen(nibName: ProtocolPOP.self)
            view.addSubview(v)
            v.protocolAgreeBlock = { [unowned self] in
                self.porotocolButton.isSelected = true
                self.wxAuthorize()
            }
            return
        }
        wxAuthorize()
    }
    
    func wxAuthorize() {
        ZMShareManager.authorize(0) { user in
            if let user = user, let uid = user.uid  {
                ZMToast.showActivity()
                LoginAPI.hadRegister(["wxOpenId" : uid]).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                    ZMToast.hiddenActivity()
                    if let ok = JSON(resp)["regState"].int {
                        if ok == 1 {
                            // 注册了
//                            router.push("xm://main/Login/psd_input", context: ["phone" : phone.text!])
                            self.wxLogin(uid)
                        } else {
                            // 没有注册
                            router.push("xm://main/Login/bind_phone", context: ["openId" : uid, "nickname" : user.nickname])
                        }
                    }
                }).disposed(by: self.disposeBag)
            } else {
                ZMToast.showToast(title: "登录失败")
            }
        }
    }
    
    func wxLogin(_ wxOpenId : String) {
        ZMToast.showActivity()
        LoginAPI.wxLogin(["wxOpenId" : wxOpenId]).rxRequest(type: LoginModels.LoginResponse.self).flatMap { resp -> Observable<CommonModels.UserInfo> in
            // 登录成功
            ZMAppShareData.share.loginInfo = resp
            // 拉取用户信息
            return MineAPI.userInfo([:]).rxRequest(type: CommonModels.UserInfo.self)
        }.subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            ZMAppShareData.share.userInfo.accept(resp)
            ZMAppShareData.share.saveUserInfo()
            self.lgoinSuccessGoNext()
        }).disposed(by: disposeBag)
    }
    
    /// 登录成功后去往的页面
    func lgoinSuccessGoNext() {
        if let vc = LoginService.shared.checkIsInfoOkAndNextVC() {
            replace(vc)
        } else {
            // 没问题可以进入app了
            ZMJumpHelper.destroy(FromVC: self, toFirstClass: LoginVC.classForCoder(), isContainSelf: true, isContainFirst: true)
            navigationController?.popViewController(animated: true)
        }
    }
    
    @IBAction func onClose(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    //MARK:--------------------delegate--------------------
}
